// 保护用户相关信息
import { login, getUserInfo, getEmployeesById } from '../../api/user'
import { getToken, setToken, removeToken } from '../../utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    // 定义一个userinfo来存放信息
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      console.log('ttt')

      state.token = token
      setToken(token)
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    //
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserinfo(state) {
      state.userInfo = {}
    }
  },
  // 异步的时候放acitons
  actions: {
    // 调用接口获取数据
    async login(store, data) {
      const res = await login(data)
      console.log(11, res)
      // 保存token
      store.commit('setToken', res)
      // 获取时间戳
      localStorage.setItem('logintime', Date.now())
    },
    // 获取用户信息
    async  getUserInfo(store) {
      const res = await getUserInfo()
      const result = await getEmployeesById(res.userId)
      store.commit('setUserInfo', { ...res, ...result })
    },
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserinfo')
    }
  }
}
